import type { AudDialogShowParams } from '@/pages/components/Aud/AudDialog';
import { CheckBox, Form, Popup, SelectBox, TextBox, } from 'devextreme-react';
import React, { useCallback, useEffect, useImperativeHandle, useRef } from 'react';
import { useState } from 'react';
import { handleStr, intl } from '@/utils';
import { useModel } from 'umi';
import { SimpleItem } from 'devextreme-react/form';
import { CpasIcon } from '~/public/cpas-ui';
import SubjectPopup from "~/public/cpas-business/components-bs/SubjectPopup"
import notify from 'devextreme/ui/notify';
import PTextBox from '../../../../../components/PTextBox';
import './index.less';
import { getAssistInfo } from './service';





const AuxiliaryPopup: React.FC<any> = React.forwardRef((props: any, ref) => {

    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;

    const { AccountDataID } = props;

    const diaParams = useRef<AudDialogShowParams & any>();
    const refsForm = useRef<any>();
    const InputRef = useRef<any>();
    const projectValuesRef = useRef<any>('');
    const projectValueRef = useRef<any>('');

    const [formAllData, setFormAllData] = useState<any>({});



    const [visible, setVisible] = useState<boolean>(false);
    const [textValue, setTextValue] = useState<string>('');
    const [selectValue, setSelectValue] = useState<string>('');
    // const [projectValue, setProjectValue] = useState<string>('');
    const [SelectHSXMLXBH, setSelectHSXMLXBH] = useState<string>('');
    // const [defaultValue, setProjectValues] = useState<string>('');
    const [accountingValue, setAccountingValue] = useState<any[]>([]);
    const [checkBoxState, setCheckBoxState] = useState<boolean>(true);

    // 选择总账科目
    const [YSKMBH, setYSKMBH] = useState<string>('');
    const [KMMC, setKMMC] = useState<string>('');
    const [KMBH, setKMBH] = useState<string>('');
    // const [AssistEditValue, setAssistEditValue] = useState<string>('')
    // const [AssistAddValue, setAssistAddValue] = useState<string>('')

    // 自定义方法
    useImperativeHandle(ref, () => ({
        show: async (params: AudDialogShowParams) => {
            diaParams.current = params;
            setVisible(true);
            setTextValue(diaParams.current?.args?.value);
            setAccountingValue(diaParams.current?.args?.items);
            setSelectValue(diaParams.current?.args?.fzzData.HSXMLXMC);
            setCheckBoxState(!diaParams.current?.args.isEdit);
            // projectValueRef.current = diaParams.current?.args?.HSXMMC;
            setFormAllData({
                projectValue: diaParams.current?.args?.HSXMMC
            });
            setKMBH(diaParams.current?.args?.fzzData.KMBH);
            if (!diaParams.current?.args?.edit) {
                setKMMC(diaParams.current?.args?.fzzData.KMMC);
                setYSKMBH(diaParams.current?.args?.fzzData.YSKMBH);
            }
        },
        close: () => { setVisible(false) }
    }));

    function EditSate(r: boolean) {
        const md5 = require('md5');
        const projectValues = formAllData.projectValue;
        const projectValue = formAllData.projectValue;
        if (r) {
            // 编辑
            diaParams.current?.okCallback({
                textValue, projectValue, selectValue, SelectHSXMLXBH, projectValues,
            });
            setVisible(false)
        } else {
            // 增加
            const projectValueMds = md5(projectValues);
            if (projectValues.length > 0) {
                const reg = /^[\s\S]*.*[^\s][\s\S]*$/
                if (reg.test(projectValues)) {
                    diaParams.current?.okCallback({
                        textValue, projectValue, selectValue, SelectHSXMLXBH, projectValues, projectValueMds, YSKMBH, KMBH, KMMC, checkBoxState
                    });
                    // setProjectValue('')
                    setVisible(false)
                } else {
                    notify('请输入核算项目名称', 'warning', 2000)
                }
            } else {
                notify('请输入核算项目名称', 'warning', 2000)
            }
        }
    }
    const onOk = useCallback(async () => {
        if (diaParams.current?.okCallback) {
            const projectValue = formAllData.projectValue;
            // 拼接科目编号
            const r = await getAssistInfo({
                dbname: dbname,
                Data_ID: AccountDataID,
                HSXMLXBH: SelectHSXMLXBH,
                KMBH,
                HSXMMC: projectValue
            })
            if (r.data?.length) return notify("该科目下已存在相同名称的辅助核算项目，无法重复新增！", "error", 2000);
            EditSate(diaParams.current?.args?.edit);
        }
    }, [textValue, selectValue, SelectHSXMLXBH, YSKMBH, KMBH, KMMC, checkBoxState, formAllData])

    const onCancel = useCallback(() => {
        setVisible(false);
        setCheckBoxState(true);
        setFormAllData({
            projectValue: ''
        });
        if (diaParams.current?.cancelCallback) {
            diaParams.current?.cancelCallback();
        }
    }, [])
    const changeCheck = useCallback((v: boolean) => {
        setCheckBoxState(v);
    }, [checkBoxState]);

    return (
        <>
            <Popup
                ref={ref}
                visible={visible}
                title={diaParams.current?.args?.title}
                width={600}
                height={400}
                wrapperAttr={{
                  class: "fix-popup-title-width"
                }}
                {...props}
                id='fzzPopupID'
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                onHiding={() => onCancel()}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '取消'),
                            onClick: () => onCancel()
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => onOk()
                        },
                    },
                ]}
                contentRender={() => (
                    <>
                        <div style={{ width: "100%", height: "100%" }} className='auxiliaryPopupBox'>
                            {
                                diaParams.current?.args?.edit
                                    ?
                                    <Form
                                        ref={refsForm}
                                        colCount={2}
                                        formData={formAllData}
                                        labelLocation={"left"}
                                        labelMode={"outside"}
                                        focusStateEnabled={true}
                                        showColonAfterLabel={true}
                                        alignItemLabels={true}
                                        className='SubjectsForm'
                                    >
                                        {/* diaParams.current?.args?.IsEnd 辅助账逻辑 */}
                                        <SimpleItem colSpan={2} label={{ text: '总 账 科 目' }}  >
                                            <TextBox value={textValue} disabled />
                                            <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                                                <CpasIcon type="icon-baobiaoxiangmubianji" />
                                            </span>
                                        </SimpleItem>
                                        <SimpleItem colSpan={2} label={{ text: '核算项目类型' }} >
                                            <SelectBox dataSource={accountingValue} disabled value={selectValue ? selectValue : accountingValue[0].HSXMLXMC} displayExpr='HSXMLXMC' valueExpr='HSXMLXMC' onSelectionChanged={(e) => {
                                                setSelectHSXMLXBH(e.selectedItem.HSXMLXBH)
                                                setSelectValue(e.selectedItem.HSXMLXMC)
                                            }}
                                            />
                                        </SimpleItem>
                                        <SimpleItem
                                            label={{ text: '核算项目名称' }}
                                            colSpan={2}
                                            dataField="projectValue"
                                            editorOptions={{
                                                valueChangeEvent: 'keyup',
                                            }}
                                        />
                                    </Form>
                                    :
                                    <Form
                                        ref={refsForm}
                                        colCount={2}
                                        formData={formAllData}
                                        labelLocation={"left"}
                                        labelMode={"outside"}
                                        focusStateEnabled={true}
                                        showColonAfterLabel={true}
                                        alignItemLabels={true}
                                        className='SubjectsForm'
                                    >
                                        {/* diaParams.current?.args?.IsEnd 辅助账逻辑 */}
                                        <SimpleItem colSpan={2} label={{ text: '总 账 科 目' }}  >
                                            <TextBox value={textValue} className="TextBox_Style" />
                                            <span style={{ position: 'absolute', right: '6px', top: "6px" }}>
                                                <CpasIcon type="icon-baobiaoxiangmubianji" onClick={() => {
                                                    InputRef.current.show({
                                                        title: "选择科目",
                                                        dbname: dbname,
                                                        Data_ID: AccountDataID,
                                                        isHasFZZ: false,
                                                        selectMode: '0',
                                                        editUser: username,
                                                        // 判断 是否为辅助账
                                                        auxiliaryState: diaParams.current?.args?.auxiliaryState,
                                                        // 选择 模式 0：单选 1：多选连机选择
                                                        okCallback: (r: any, v: any) => {
                                                            console.log(r, v, 'r------rrrrrrrrr');
                                                            // const PKMBH = r.PKMBH === '' ? '' : r[0].PKMBH ? handleStr(r[0].PKMBH) : handleStr(r.PKMBH);
                                                            // const KMMC = r.KMMC ? r.KMMC : r[0].KMMC;
                                                            const KMMC = r.displayName ? r.displayName : r[0].YSKMBH + '-' + r[0].YSKMMC;
                                                            // 获取选中的数据
                                                            setKMBH(r.KMBH ? r.KMBH : r[0].KMBH);
                                                            setKMMC(r.KMMC ? r.KMMC : r[0].KMMC);
                                                            setYSKMBH(r.YSKMBH ? r.YSKMBH : r[0].YSKMBH);
                                                            setTextValue(KMMC);
                                                            setAccountingValue(v);
                                                        },
                                                    });
                                                }} />
                                            </span>
                                        </SimpleItem>
                                        <SimpleItem colSpan={2} label={{ text: '核算项目类型' }} >
                                            <SelectBox dataSource={accountingValue} value={selectValue ? selectValue : accountingValue[0]?.HSXMLXMC}
                                                displayExpr='HSXMLXMC' valueExpr='HSXMLXMC' onSelectionChanged={(e) => {
                                                    setSelectHSXMLXBH(e.selectedItem.HSXMLXBH)
                                                    setSelectValue(e.selectedItem.HSXMLXMC)
                                                }} />
                                        </SimpleItem>
                                        <SimpleItem
                                            label={{ text: '核算项目名称' }}
                                            colSpan={2}
                                            dataField="projectValue"
                                            editorOptions={{
                                                valueChangeEvent: 'keyup',
                                            }}
                                        />
                                    </Form>
                            }
                            {!diaParams.current?.args.edit && <div className='isAddMoreYear'>
                                <span style={{ marginLeft: '8px', marginRight: '10px', whiteSpace: 'nowrap' }}>是否增加多年度:</span><CheckBox value={checkBoxState}
                                    onValueChange={(e: any) => {
                                        // setCheckBoxState(e);
                                        changeCheck(e);
                                    }} /></div>}
                        </div>
                    </>

                )}
            />
            <SubjectPopup ref={InputRef}  
              wrapperAttr={{
                class: "fix-popup-title-width"
              }}
            />
        </>
    );
});


export default AuxiliaryPopup